import axios from "axios"
import { BASE_URL, TIME_OUT } from "../config/config"
import { useMainstore } from "../../stores/modules/mainStores"

const mainStore = useMainstore();

class My_Axios
{
    constructor(baseURL,timeout=1000)
    {
        this.instance = axios.create({
            baseURL,
            timeout
        })

         //放到拦截器内更好：请求时开启加载，响应后取消加载
        this.instance.interceptors.request.use(config => {
            mainStore.isLoad = true;
            return config;
        }, err => {
            mainStore.isLoad = false;
            return err;
        })
        
        //响应拦截
        this.instance.interceptors.response.use(config => {
            mainStore.isLoad = false;
            return config;
        }, err => {
            mainStore.isLoad = false;
            return err;
        })
    }
    
    //返回一个promise对象
    //每个网络请求都会经过request，在request开启加载，也可以放到拦截器内

    request(config)
    {
        return new Promise((resolve, reject) =>
        {
            this.instance.request(config).then(res => {
                resolve(res.data);
            }).catch(err => {
                reject(err);
              })    
        })
    }

    get(config)
    {
        return this.request({
            ...config,method:"get"
        });
    }

    post(config)
    {
        return this.request({
            ...config,method:"post"
        })
    }
}
 
const myAxios =  new My_Axios(BASE_URL, TIME_OUT);

export default myAxios 